//
//  AppDelegate.swift
//  HuaYun
//
//  Created by enghou on 2018/6/27.
//  Copyright © 2018年 xyxorigation. All rights reserved.
//

import UIKit

import IQKeyboardManagerSwift

import UserNotifications

//import PhotosUI
//
//import Security

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,JPUSHRegisterDelegate,UNUserNotificationCenterDelegate {
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) {
        if notification.request.trigger is UNPushNotificationTrigger {
            let userInfo = notification.request.content.userInfo
            JPUSHService.handleRemoteNotification(userInfo)
        }else {
            //本地通知
        }
        //需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
        completionHandler(Int(UNNotificationPresentationOptions.alert.rawValue))
    }
    
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void){
        
        completionHandler(UNNotificationPresentationOptions.alert)
        
    }
    
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void){
        let userInfo = response.notification.request.content.userInfo
        print("userInfo10:\(userInfo)")
        completionHandler()
    }
    
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {
        
        let userInfo = response.notification.request.content.userInfo
        if response.notification.request.trigger is UNPushNotificationTrigger {
            JPUSHService.handleRemoteNotification(userInfo)
        }
        completionHandler()
    }
    
    var window: UIWindow?

    
    func check()->Bool{

        return ValidationChecker.valid()
    }
    
//    var types: [JSON] = []
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        JPUSHService.setup(withOption: launchOptions, appKey: "47c2658e91fc84cd909206ba", channel: "app store", apsForProduction: false)
        if #available(iOS 10.0, *) {
            let center = UNUserNotificationCenter.current()
            center.delegate = self
            center.requestAuthorization(options: UNAuthorizationOptions(arrayLiteral: [.alert,.badge,.sound])) { (result, error) in
                
            }
        } else if #available(iOS 8.0, *) {
            let types = UIUserNotificationType.badge.rawValue |
                UIUserNotificationType.sound.rawValue |
                UIUserNotificationType.alert.rawValue
            
            let entity = JPUSHRegisterEntity()
            entity.types = Int(types)
            
            let category = UIMutableUserNotificationCategory.init()
            category.identifier = "reply"
            entity.categories = Set.init([category])
            JPUSHService.register(forRemoteNotificationTypes: types, categories: [category])
        }
        
        
        
        

        NotificationCenter.default.addObserver(self, selector: #selector(handleimg(not:)), name: UIApplication.userDidTakeScreenshotNotification, object: nil)
        
        SVProgressHUD.setDefaultStyle(.dark)
        
        SVProgressHUD.setDefaultMaskType(.clear)
        
        SVProgressHUD.setDefaultAnimationType(.native)
        
        IQKeyboardManager.shared.enable = true
        //控制点击背景是否收起键盘
        IQKeyboardManager.shared.shouldResignOnTouchOutside = true
        //控制键盘上的工具条文字颜色是否用户自定义
        IQKeyboardManager.shared.shouldShowToolbarPlaceholder = true
        //       IQKeyboardManager.sharedManager().shouldToolbarUsesTextFieldTintColor = true
        //将右边Done改成完成
        IQKeyboardManager.shared.toolbarDoneBarButtonItemText = "完成"
        // 控制是否显示键盘上的工具条
        IQKeyboardManager.shared.enableAutoToolbar = true
        //最新版的设置键盘的returnKey的关键字 ,可以点击键盘上的next键，自动跳转到下一个输入框，最后一个输入框点击完成，自动收起键盘
        IQKeyboardManager.shared.toolbarManageBehaviour = .byPosition
        
        if User.id.count == 0 {
            let login = LoginViewController()

            let navi = UINavigationController.init(rootViewController: login)

            self.window?.rootViewController = navi
        }
//        self.window?.rootViewController = ScanBinaryCodeViewController()
        
//        PHPhotoLibrary.shared().register(self)
//        let bx = RequestBaoXiaoViewController()
//        let scan = ScanBinaryCodeViewController()
//        self.window?.rootViewController = scan
        return true
    }
    
    @objc func handleimg(not: Notification)->Void{

    }
    
    func savephoto(img: UIImage,vc: UIViewController?)->Void{

    }
    
    func getCurrentPhotoCollection(with name: String)->PHAssetCollection?{
        let result = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumRegular, options: nil)
        for i in 0 ..< result.count {
            let asset = result[i]
            if asset.localizedTitle == name {
                return asset
            }
        }
        return nil
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print(error)
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        JPUSHService.registerDeviceToken(deviceToken)
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
        JPUSHService.handleRemoteNotification(userInfo)
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        JPUSHService.handleRemoteNotification(userInfo)
        completionHandler(.newData)
//        completionHandler(UIBackgroundFetchResult.newData)
    }
    
    
    
}

